package friendService

import (
	"chart.zozoo.net/app/models"
	"chart.zozoo.net/app/service/friendApplyService"
	"chart.zozoo.net/app/service/userService"
	"chart.zozoo.net/core/mysql"
	"errors"
)

// ApplyAdd 申请添加好友
func ApplyAdd(uuid, friendUuid string) (err error) {

	//获取用户信息
	myUserInfo, err := userService.InfoByUuid(uuid)
	if err != nil {
		return err
	}

	//好友的用户信息
	friendUserInfo, err := userService.InfoByUuid(friendUuid)
	if err != nil {
		return err
	}

	//获取申请状态
	applyInfo, err := friendApplyService.ApplyInfo(myUserInfo.Id, friendUserInfo.Id)
	if err != nil {
		return err
	}
	if applyInfo.Id != 0 {
		//存在申请记录，判断状态
		switch applyInfo.Status {
		case 1:
			return errors.New("已经是好友了，无需重复操作")
		case 0:
			return errors.New("已经申请过，等待对方同意")
		}
	}

	//添加申请记录
	apply := &models.UserFriendsApply{
		Uid:    myUserInfo.Id,
		Fid:    friendUserInfo.Id,
		Status: 0,
	}
	res := mysql.MysqlClient.Create(apply)
	if res.Error != nil {
		return res.Error
	}

	return nil
}
